package com.example.androidcoursedesing;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivityExample extends AppCompatActivity implements View.OnClickListener {

    private OkHttpClient client;
    private ImageView image_iv;

    //为了能够实现子线程与主线程通信，需要使用handler
    private  Handler handler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 100:
                    Bitmap obj = (Bitmap) msg.obj;
                    //更新UI
                    image_iv.setImageBitmap(obj);
                    break;
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_example);
        Button get_bt = findViewById(R.id.get_bt);
        Button post_json_bt = findViewById(R.id.post_json_bt);
        Button load_image_bt = findViewById(R.id.load_image_bt);
         image_iv = findViewById(R.id.image_iv);
        load_image_bt.setOnClickListener(this);
        get_bt.setOnClickListener(this);
        post_json_bt.setOnClickListener(this);
        initOkHttp();

    }

    private void initOkHttp()  {
        //1.创建OkhttpClient对象
         client = new OkHttpClient();


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case  R.id.get_bt:
                //2.创建request对象，设置一个url地址，请求方式
                Request request = new Request.Builder()
                        .get()
                        .url("https://www.baidu.com")
                        .build();
                //3.创建一个call对象，参数就是request对象
                Call call = client.newCall(request);
                //同步请求
//                try {
//                    execute(call);
//                } catch (IOException e) {
//                    throw new RuntimeException(e);
//                }

                //异步请求
               enqueue(call);

                break;
            case R.id.post_json_bt:
                //构造 RequestBody 需要指定MediaType，用于描述请求/响应 body 的内容类型
                MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
                String data = "{\"name\":\"张三\",\"age\":\"18\"}";
                String url= "http://10.111.34.2:8089/okhttp/toJson";
                //创建请求
                Request request2 = new Request.Builder()
                        .post(RequestBody.create(mediaType, data))
                        .url(url)
                        .build();
                //发起请求
                Call call2 = client.newCall(request2);
                //采用异步请求
                call2.enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        Log.i("network",e.getMessage());
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        String content = response.body().string();
                        Log.i("network","返回的数据："+content);
                    }
                });
                break;
            //下载图片并显示到imageview控件
            case  R.id.load_image_bt:
                Request request3 = new Request.Builder()
                        .url("https://p.qqan.com/up/2022-5/16539667599197004.jpg")
                        .get()
                        .build();
                client.newCall(request3).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {

                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                        InputStream is = response.body().byteStream();
                        //使用 BitmapFactory 的 decodeStream 将图片的输入流直接转换为 Bitmap
                         Bitmap bitmap = BitmapFactory.decodeStream(is);
                        //image_iv.setImageBitmap(bitmap);
                        //在主线程中操作UI
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                //然后将Bitmap设置到 ImageView 中
//                                image_iv.setImageBitmap(bitmap);
//                            }
//                        });
                        //使用handler通知主线
                        //创建消息对象
                        Message msg = Message.obtain();
                        msg.obj=bitmap;
                        msg.what=100;
                        //使用handler传递消息
                        handler.sendMessage(msg);
                        is.close();


                    }
                });


                break;

        }

    }

    private void enqueue(Call call) {
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String content = response.body().string();
                Log.i("network",content);
            }
        });
    }

    private void execute(Call call) throws IOException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //同步请求
                    Response response = call.execute();
                    String string = response.body().string();
                    System.out.println(string);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
}